<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Review Rating Synthesis
 * @version 	1.0
 * @author 		Nguyen Dinh Nhat <nguyendnhat@gmail.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
include_once(dirname(__FILE__)."/classes/Zalbum.php");
/**
 * Once field in tab ZadminEmailEvent
 * @author Nguyen Dinh Nhat <nguyendnhat@gmail.com>
 *
 */
class ZadminAlbum extends ZadminTab {
	private $_Album;
	public $childTable = 'zgallery_album';
	/**
	 * Construct
	 * @return <type>
	 */
	protected $identifiersDnd = array('id_product' => 'id_product', 'id_category' => 'id_category_to_move','id_cms_category' => 'id_cms_category_to_move', 'id_cms' => 'id_cms','id_zgallery_album'=>'id_zgallery_album');
	
	public function __construct()
	{
		global $cookie;
		$this->table = 'zgallery_album';
	 	$this->className = 'Zalbum';
	 	$this->edit = true;
	 	$this->view = true;
	 	$this->lang=true;
	 	$this->delete = true;
		$this->fieldsDisplay = array(
			'id_zgallery_album' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 53),
			'image' => array('title' => $this->l('Photo'), 'align' => 'center', 'image' => 'zgallery/img/ab/', 'width' => 45, 'orderby' => false, 'filter' => false, 'search' => false),
			'name' => array('title' => $this->l('Title'), 'align' => 'center', 'width' => 250),
			'nb_view' => array('title' => $this->l('Number View'), 'align' => 'center', 'width' => 23),
			'nb_like' => array('title' => $this->l('Number Like'), 'align' => 'center', 'width' => 23),
			'date_add' => array('title' => $this->l('Create Date'), 'type'=>'datetime' ,'align' => 'right', 'width' => 100),
			'active'=>array('title'=>$this->l('Status'),'width'=>25,'align'=>'center','type'=>'bool','orderdy'=>false,'callback'=>'printNewsIconActive'),
		);
		$this->_Album = ZadminGallery::getCurrentAlbum();
		$this->_filter = 'AND `id_parent` = '.(int)($this->_Album->id);
		$this->_select = 'position ';
		$this->_defaultOrderBy = 'position';
		parent::__construct();
	}
	/**
	 get new Id create 
	 */
	function getNewId()
	{
		$rs = Db::getInstance()->ExecuteS('SELECT id_zgallery_album FROM '._DB_PREFIX_.'zgallery_album ORDER BY id_zgallery_album DESC LIMIT 0,1');
		$row = $rs[0];
		return $row['id_zgallery_album']+1;
	}
	/**
	 * Display image aside object form
	 *
	 * @param integer $id Object id
	 * @param string $image Local image filepath
	 * @param integer $size Image width
	 * @param integer $id_image Image id (for products with several images)
	 * @param string $token Employee token used in the image deletion link
	 * @param boolean $disableCache When turned on a timestamp will be added to the image URI to disable the HTTP cache
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	public function _displayImage($id, $image,$DIR ,$size, $id_image = NULL, $token = NULL, $disableCache = false)
	{
		global $currentIndex;
		if (!isset($token) OR empty($token))
			$token = $this->token;
		
		if ($id AND file_exists($image))
			echo '
			<div id="image" >
				<img class="imgm" style="width:'.$size.'px" alt="" src="'.$DIR.'">
				<p align="center">'.$this->l('File size').' '.(filesize($image) / 1000).'kb</p>
			</div><br />';
	}
	/** 
	 * NHững thông tin được update sẽ lưu tại đây
	 * @param $token
	 */
	public function postProcess($token = NULL)
	{
		global $currentIndex;
		$_GET['tabs']=0;
		if (Tools::isSubmit('changeActive') and Tools::getValue('id_zgallery_album')){
			$id_zgallery_album=(int)Tools::getValue('id_zgallery_album');
			$obj = new Zalbum($id_zgallery_album);
			$update = Db::getInstance()->Execute(
				'UPDATE `'._DB_PREFIX_.'zgallery_album` 
				SET active = '.($obj->active?0:1).' 
				WHERE `id_zgallery_album` = '.(int)($obj->id));
			if (!$update)
				$this->_errors[] = Tools::displayError('An error occurred while updating customer.');
			$id_parent = Tools::getValue('id_zgallery_album');
			$category_url = empty($id_zgallery_album) ? '' : '&id_zgallery_album='.$id_parent;
			Tools::redirectAdmin($currentIndex.'&conf=5&token='.$this->token.$category_url);
		}elseif (isset($_GET['position']))
		{
			if ($this->tabAccess['edit'] !== '1')
				$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
			elseif (!Validate::isLoadedObject($object = new Category((int)(Tools::getValue($this->identifier, Tools::getValue('id_category_to_move', 1))))))
				$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			if (!$object->updatePosition((int)(Tools::getValue('way')), (int)(Tools::getValue('position'))))
				$this->_errors[] = Tools::displayError('Failed to update the position.');
			else {
				Tools::redirectAdmin($currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.(($id_category = (int)(Tools::getValue($this->identifier, Tools::getValue('id_category_parent', 1)))) ? ('&'.$this->identifier.'='.$id_category) : '').'&token='.Tools::getAdminTokenLite('AdminCatalog'));
			}
		}
		if (Tools::isSubmit('submitAdd'.$this->table)) {
			$obj = $this->loadObject(true);
			if ($obj->id==NULL) 
			{
				$target = dirname(__FILE__).'/img/ab/';
				$img_ext = substr($_FILES['image']['name'], strripos($_FILES['image']['name'], '.')); // strip name
				if(Tools::getValue('id_zgallery_album')){
					$newfilename = 'Album_'.$this->getFieldValue($obj, 'id_zgallery_album').$img_ext;			
				}else{
					$newfilename = 'Album_'.$this->getNewId().$img_ext;
				}
				$targetimg = $target.$newfilename;
				$fileimg = $_FILES['image']['name'];
				if($fileimg != ''){
					if($this->check($fileimg)){
						if(move_uploaded_file($_FILES['image']['tmp_name'],$targetimg)==true){
							$_POST['image'] = $newfilename;
						}
					}else{
//						$this->error = 1;
						 $this->_errors[] = Tools::displayError('Images format not recognized, allowed formats are: .gif, .jpeg, .jpg, .png');
					}			
				}
			}
			else {
				if ($_FILES['image']['name']!="") {
					$target = dirname(__FILE__).'/img/ab/';
					$img_ext = substr($_FILES['image']['name'], strripos($_FILES['image']['name'], '.')); // strip name
					if(Tools::getValue('id_zgallery_album')){
						$newfilename = 'Album_'.$this->getFieldValue($obj, 'id_zgallery_album').$img_ext;			
					}else{
						$newfilename = 'Album_'.$this->getNewId().$img_ext;
					}
					$targetimg = $target.$newfilename;
					$fileimg = $_FILES['image']['name'];
					if($fileimg != ''){
						if($this->check($fileimg)){
							if(move_uploaded_file($_FILES['image']['tmp_name'],$targetimg)==true){
								$_POST['image'] = $newfilename;
							}
						}else{
//							$this->error = 1;
							 $this->_errors[] = Tools::displayError('Images format not recognized, allowed formats are: .gif, .jpeg, .jpg, .png');
						}			
					}
				}
				else  
				$_POST['image'] = Zalbum::getNameImage ($obj->id);
			}
			
			$_POST['level_depth'] = Zalbum::getLevelDepth ($_POST['id_parent']);
//			if ($_POST['id_zgallery_album'] == 1) {
//				$_POST['id_parent'] = 0;
//				$_POST['level_depth'] = 0;
//				$_POST['submitAddzgallery_albumAndBackToParent'] = NULL;
//			}
		}
		$this->_postProcess ();
	}
	/**
	 * Đổi tên cho file được upload
	 * @param $id
	 */
	public function renameImage ($id) {
		$nameImageOld = Zalbum::getNameImage ($id);
		$nameImage = substr($nameImageOld, strripos($nameImageOld, '.')); // strip name
		$query = '
			UPDATE `'._DB_PREFIX_.'zgallery_album` SET `image`="Album_'.$id.$nameImage.'" WHERE (`id_zgallery_album`='.$id.')
		';
		$results = Db::getInstance()->Execute($query);
		$target = dirname(__FILE__).'/img/ab/';
		rename($target.$nameImageOld, $target."Album_$id$nameImage");
		if (file_exists($target.$nameImage) AND !unlink($target.$nameImage))
			return true;
		return false;
	}
	/**
	 * Giống với postProcess của hàm cha
	 * Nhưng thay đổi ở hàm delete
	 */
	public function _postProcess()
	{
		global $currentIndex, $cookie;
		if (!isset($this->table))
			return false;
		
		// set token
		$token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;

		// Sub included tab postProcessing
		$this->includeSubTab('postProcess', array('status', 'submitAdd1', 'submitDel', 'delete', 'submitFilter', 'submitReset'));

		/* Delete object image */
		if (isset($_GET['deleteImage']))
		{
			if (Validate::isLoadedObject($object = $this->loadObject()))
				if (($object->deleteImage()))
					Tools::redirectAdmin($currentIndex.'&add'.$this->table.'&'.$this->identifier.'='.Tools::getValue($this->identifier).'&conf=7&token='.$token);
			$this->_errors[] = Tools::displayError('An error occurred during image deletion (cannot load object).');
		}

		/* Delete object */
		elseif (isset($_GET['delete'.$this->table]))
		{
			if ($this->tabAccess['delete'] === '1')
			{
				if (Validate::isLoadedObject($object = $this->loadObject()) AND isset($this->fieldImageSettings))
				{
					// check if request at least one object with noZeroObject
					if (isset($object->noZeroObject) AND sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1)
						$this->_errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.');
					else
					{
						$id = $_GET['id_zgallery_album']; 
						$name = Zalbum::getImageName ($id);
						$arr = Zalbum::getParents ($id);
						
						$category_url = '&id_zgallery_album='.$arr['id_parent']; 
						
						Zalbum::_deleteImage($id,$name);
						if ($this->deleted)
						{
							$object->deleteImage();
							$object->deleted = 1;
							if ($object->update())
								Tools::redirectAdmin($currentIndex.'&conf=1&token='.$token.$category_url);
						}
						elseif ($object->delete())
							Tools::redirectAdmin($currentIndex.'&conf=1&token='.$token.$category_url);
						$this->_errors[] = Tools::displayError('An error occurred during deletion.');
					}
				}
				else
					$this->_errors[] = Tools::displayError('An error occurred while deleting object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			}
			else
				$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
		}

		/* Change object statuts (active, inactive) */
		elseif ((isset($_GET['status'.$this->table]) OR isset($_GET['status'])) AND Tools::getValue($this->identifier))
		{
			if ($this->tabAccess['edit'] === '1')
			{
				if (Validate::isLoadedObject($object = $this->loadObject()))
				{
					if ($object->toggleStatus())
						Tools::redirectAdmin($currentIndex.'&conf=5'.((($id_category = (int)(Tools::getValue('id_category'))) AND Tools::getValue('id_product')) ? '&id_category='.$id_category : '').'&token='.$token);
					else
						$this->_errors[] = Tools::displayError('An error occurred while updating status.');
				}
				else
					$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			}
			else
				$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
		}
		/* Move an object */
		elseif (isset($_GET['position']))
		{
			if ($this->tabAccess['edit'] !== '1')
				$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
			elseif (!Validate::isLoadedObject($object = $this->loadObject()))
				$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			elseif (!$object->updatePosition((int)(Tools::getValue('way')), (int)(Tools::getValue('position'))))
				$this->_errors[] = Tools::displayError('Failed to update the position.');
			else
				Tools::redirectAdmin($currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.(($id_category = (int)(Tools::getValue($this->identifier))) ? ('&'.$this->identifier.'='.$id_category) : '').'&token='.$token);
				 Tools::redirectAdmin($currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.((($id_category = (int)(Tools::getValue('id_category'))) AND Tools::getValue('id_product')) ? '&id_category='.$id_category : '').'&token='.$token);
		}
		/* Delete multiple objects */
		elseif (Tools::getValue('submitDel'.$this->table))
		{
			
			if ($this->tabAccess['delete'] === '1')
			{
				
				if (isset($_POST[$this->table.'Box']))
				{
					
					$object = new $this->className();
					if (isset($object->noZeroObject) AND
						// Check if all object will be deleted
						(sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 OR sizeof($_POST[$this->table.'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject)))))
						$this->_errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.');
					else
					{
						
						$result = true;
						if ($this->deleted)
						{
							foreach(Tools::getValue($this->table.'Box') as $id)
							{
								$toDelete = new $this->className($id);
								$toDelete->deleted = 1;
								$result = $result AND $toDelete->update();
							}
						}
						else
							$result = $object->deleteSelection(Tools::getValue($this->table.'Box'));
						
						if ($result)
							Tools::redirectAdmin($currentIndex.'&conf=2&token='.$token);
						$this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
					}
				}
				else
					$this->_errors[] = Tools::displayError('You must select at least one element to delete.');
			}
			else
				$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
		}

		/* Create or update an object */
		elseif (Tools::getValue('submitAdd'.$this->table))
		{
			/* Checking fields validity */
			$this->validateRules();
			if (!sizeof($this->_errors))
			{
				$id = (int)(Tools::getValue($this->identifier));

				/* Object update */
				if (isset($id) AND !empty($id))
				{
					if ($this->tabAccess['edit'] === '1' OR ($this->table == 'employee' AND $cookie->id_employee == Tools::getValue('id_employee') AND Tools::isSubmit('updateemployee')))
					{
						$object = new $this->className($id);
						if (Validate::isLoadedObject($object))
						{
							/* Specific to objects which must not be deleted */
							if ($this->deleted AND $this->beforeDelete($object))
							{
								// Create new one with old objet values
								$objectNew = new $this->className($object->id);
								$objectNew->id = NULL;
								$objectNew->date_add = '';
								$objectNew->date_upd = '';

								// Update old object to deleted
								$object->deleted = 1;
								$object->update();

								// Update new object with post values
								$this->copyFromPost($objectNew, $this->table);
								$result = $objectNew->add();
								if (Validate::isLoadedObject($objectNew))
									$this->afterDelete($objectNew, $object->id);
							}
							else
							{
								$this->copyFromPost($object, $this->table);
								$result = $object->update();
								$this->afterUpdate($object);
							}
							if (!$result)
								$this->_errors[] = Tools::displayError('An error occurred while updating object.').' <b>'.$this->table.'</b> ('.Db::getInstance()->getMsgError().')';
							elseif ($this->postImage($object->id) AND !sizeof($this->_errors))
							{
								
								$parent_id = (int)(Tools::getValue('id_parent', 1));
								// Specific back redirect
								if ($back = Tools::getValue('back'))
									Tools::redirectAdmin(urldecode($back).'&conf=4');
								// Specific scene feature
								if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1')
									Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&updatescene&token='.$token);
								// Save and stay on same form
								if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
									Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&update'.$this->table.'&token='.$token);
								// Save and back to parent
								if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
									Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=4&token='.$token);
								// Default behavior (save and back)
								Tools::redirectAdmin($currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=4&token='.$token);
							}
						}
						else
							$this->_errors[] = Tools::displayError('An error occurred while updating object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
					}
					else
						$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
				}

				/* Object creation */
				else
				{
					if ($this->tabAccess['add'] === '1')
					{
						$object = new $this->className();
						$this->copyFromPost($object, $this->table);
						if (!$object->add())
							$this->_errors[] = Tools::displayError('An error occurred while creating object.').' <b>'.$this->table.' ('.mysql_error().')</b>';
						elseif (($_POST[$this->identifier] = $object->id /* voluntary */) AND $this->postImage($object->id) AND !sizeof($this->_errors) AND $this->_redirect)
						{
							$this->renameImage ($this->getNewId()-1);
							$parent_id = (int)(Tools::getValue('id_parent', 1));
							$this->afterAdd($object);
							// Save and stay on same form
							if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
								Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=3&update'.$this->table.'&token='.$token);
							// Save and back to parent
							if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
								Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$token);
							// Default behavior (save and back)
							Tools::redirectAdmin($currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=3&token='.$token);
						}
					}
					else
						$this->_errors[] = Tools::displayError('You do not have permission to add here.');
				}
			}
			$this->_errors = array_unique($this->_errors);
		}

		/* Cancel all filters for this tab */
		elseif (isset($_POST['submitReset'.$this->table]))
		{
			
			$filters = $cookie->getFamily($this->table.'Filter_');
			foreach ($filters AS $cookieKey => $filter)
				if (strncmp($cookieKey, $this->table.'Filter_', 7 + Tools::strlen($this->table)) == 0)
					{
						$key = substr($cookieKey, 7 + Tools::strlen($this->table));
						/* Table alias could be specified using a ! eg. alias!field */
						$tmpTab = explode('!', $key);
						$key = (count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0]);
						if (array_key_exists($key, $this->fieldsDisplay))
							unset($cookie->$cookieKey);
					}
			if (isset($cookie->{'submitFilter'.$this->table}))
				unset($cookie->{'submitFilter'.$this->table});
			if (isset($cookie->{$this->table.'Orderby'}))
				unset($cookie->{$this->table.'Orderby'});
			if (isset($cookie->{$this->table.'Orderway'}))
				unset($cookie->{$this->table.'Orderway'});
			unset($_POST);
		}

		/* Submit options list */
		elseif (Tools::getValue('submitOptions'.$this->table))
		{
			$this->updateOptions($token);
		}

		/* Manage list filtering */
		elseif (Tools::isSubmit('submitFilter'.$this->table) OR $cookie->{'submitFilter'.$this->table} !== false)
		{
			$_POST = array_merge($cookie->getFamily($this->table.'Filter_'), (isset($_POST) ? $_POST : array()));
			
			
			foreach ($_POST AS $key => $value)
			{
				/* Extracting filters from $_POST on key filter_ */
				if ($value != NULL AND !strncmp($key, $this->table.'Filter_', 7 + Tools::strlen($this->table)))
				{
					$key = Tools::substr($key, 7 + Tools::strlen($this->table));
					/* Table alias could be specified using a ! eg. alias!field */
					$tmpTab = explode('!', $key);
					$filter = count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0];
					if ($field = $this->filterToField($key, $filter))
					{
						$type = (array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false));
						if (($type == 'date' OR $type == 'datetime') AND is_string($value))
							$value = unserialize($value);
						$key = isset($tmpTab[1]) ? $tmpTab[0].'.`'.bqSQL($tmpTab[1]).'`' : '`'.bqSQL($tmpTab[0]).'`';
						if (array_key_exists('tmpTableFilter', $field))
							$sqlFilter = & $this->_tmpTableFilter;
						elseif (array_key_exists('havingFilter', $field))
							$sqlFilter = & $this->_filterHaving;
						else
							$sqlFilter = & $this->_filter;

						/* Only for date filtering (from, to) */
						if (is_array($value))
						{
							if (isset($value[0]) AND !empty($value[0]))
							{
								if (!Validate::isDate($value[0]))
									$this->_errors[] = Tools::displayError('\'from:\' date format is invalid (YYYY-MM-DD)');
								else
									$sqlFilter .= ' AND '.$key.' >= \''.pSQL(Tools::dateFrom($value[0])).'\'';
							}

							if (isset($value[1]) AND !empty($value[1]))
							{
								if (!Validate::isDate($value[1]))
									$this->_errors[] = Tools::displayError('\'to:\' date format is invalid (YYYY-MM-DD)');
								else
									$sqlFilter .= ' AND '.$key.' <= \''.pSQL(Tools::dateTo($value[1])).'\'';
							}
						}
						else
						{
							$sqlFilter .= ' AND ';
							if ($type == 'int' OR $type == 'bool')
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`' OR $key == '`active`') ? 'a.' : '').pSQL($key).' = '.(int)($value).' ';
							elseif ($type == 'decimal')
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' = '.(float)($value).' ';
							elseif ($type == 'select')
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' = \''.pSQL($value).'\' ';
							else
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' LIKE \'%'.pSQL($value).'%\' ';
						}
					}
				}
			}
		}
		elseif (Tools::isSubmit('submitFields') AND $this->requiredDatabase AND $this->tabAccess['add'] === '1' AND $this->tabAccess['delete'] === '1')
		{
			if (!is_array($fields = Tools::getValue('fieldsBox')))
				$fields = array();

			$object = new $this->className();
			if (!$object->addFieldsRequiredDatabase($fields))
				$this->_errors[] = Tools::displayError('Error in updating required fields');
			else
				Tools::redirectAdmin($currentIndex.'&conf=4&token='.$token);
		}
	}
	
/* End Override Admin tab*/
	public $upload_type	= array('jpg', 'jpeg', 'gif', 'png');
	function check($filename){
		$start	= strrpos($filename, ".");
		if ( $start < strlen($filename) ){
			$user_type	= strtolower(substr($filename, $start+1));
			if ( in_array($user_type, $this->upload_type) ){
				return true;
			}
		}
		return false;
	}
	/**
	 * Manage page display (form, list...)
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	public function displayList($token = NULL)
	{
		global $currentIndex;
		/* Display list header (filtering, pagination and column names) */
		$this->displayListHeader($token);
		if (!sizeof($this->_list))
			echo '<tr><td class="center" colspan="'.(sizeof($this->fieldsDisplay) + 2).'">'.$this->l('No items found').'</td></tr>';

		/* Show the content of the table */
		$this->displayListContent($token);

		/* Close list table and submit button */
		$this->displayListFooter($token);
	}
	/**
	 * Hiển thị thông tin ơ list content
	 * @param unknown_type $token
	 */
	public function displayListContent($token = NULL)
	{
		/* Display results in a table
		 *
		 * align  : determine value alignment
		 * prefix : displayed before value
		 * suffix : displayed after value
		 * image  : object image
		 * icon   : icon determined by values
		 * active : allow to toggle status
		 */

		global $currentIndex, $cookie;
		$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));

		$id_category = 1; // default categ

		$irow = 0;
		if ($this->_list AND isset($this->fieldsDisplay['position']))
		{
			$positions = array_map(create_function('$elem', 'return (int)($elem[\'position\']);'), $this->_list);
			sort($positions);
		}
		if ($this->_list)
		{
			$isCms = false;
			if (preg_match('/cms/Ui', $this->identifier))
				$isCms = true;
			$keyToGet = 'id_'.($isCms ? 'cms_' : '').'category'.(in_array($this->identifier, array('id_category', 'id_cms_category')) ? '_parent' : '');
			foreach ($this->_list AS $tr)
			{
				$id = $tr[$this->identifier];
				echo '<tr'.(array_key_exists($this->identifier,$this->identifiersDnd) ? ' id="tr_'.(($id_category = (int)(Tools::getValue('id_'.($isCms ? 'cms_' : '').'category', '1'))) ? $id_category : '').'_'.$id.'_'.$tr['position'].'"' : '').($irow++ % 2 ? ' class="alt_row"' : '').' '.((isset($tr['color']) AND $this->colorOnBackground) ? 'style="background-color: '.$tr['color'].'"' : '').'>
							<td class="center">';
				if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
					echo '<input type="checkbox" name="'.$this->table.'Box[]" value="'.$id.'" class="noborder" />';
				echo '</td>';
				foreach ($this->fieldsDisplay AS $key => $params)
				{
					$tmp = explode('!', $key);
					$key = isset($tmp[1]) ? $tmp[1] : $tmp[0];
					echo '
					<td '.(isset($params['position']) ? ' id="td_'.(isset($id_category) AND $id_category ? $id_category : 0).'_'.$id.'"' : '').' class="'.((!isset($this->noLink) OR !$this->noLink) ? 'pointer' : '').((isset($params['position']) AND $this->_orderBy == 'position')? ' dragHandle' : ''). (isset($params['align']) ? ' '.$params['align'] : '').'" ';
					if (!isset($params['position']) AND (!isset($this->noLink) OR !$this->noLink))
						echo ' onclick="document.location = \''.$currentIndex.'&'.$this->identifier.'='.$id.($this->view? '&view' : '&update').$this->table.'&token='.($token!=NULL ? $token : $this->token).'\'">'.(isset($params['prefix']) ? $params['prefix'] : '');
					else
						echo '>';
					if (isset($params['active']) AND isset($tr[$key]))
						$this->_displayEnableLink($token, $id, $tr[$key], $params['active'], Tools::getValue('id_category'), Tools::getValue('id_product'));
					elseif (isset($params['activeVisu']) AND isset($tr[$key]))
						echo '<img src="../img/admin/'.($tr[$key] ? 'enabled.gif' : 'disabled.gif').'"
						alt="'.($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')).'" title="'.($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')).'" />';
					elseif (isset($params['position']))
					{
						if ($this->_orderBy == 'position' AND $this->_orderWay != 'DESC')
						{
							echo '<a'.(!($tr[$key] != $positions[sizeof($positions) - 1]) ? ' style="display: none;"' : '').' href="'.$currentIndex.
									'&'.$keyToGet.'='.(int)($id_category).'&'.$this->identifiersDnd[$this->identifier].'='.$id.'
									&way=1&position='.(int)($tr['position'] + 1).'&token='.($token!=NULL ? $token : $this->token).'">
									<img src="../img/admin/'.($this->_orderWay == 'ASC' ? 'down' : 'up').'.gif"
									alt="'.$this->l('Down').'" title="'.$this->l('Down').'" /></a>';
							echo '<a'.(!($tr[$key] != $positions[0]) ? ' style="display: none;"' : '').' href="'.$currentIndex.
									'&'.$keyToGet.'='.(int)($id_category).'&'.$this->identifiersDnd[$this->identifier].'='.$id.'
									&way=0&position='.(int)($tr['position'] - 1).'&token='.($token!=NULL ? $token : $this->token).'">
									<img src="../img/admin/'.($this->_orderWay == 'ASC' ? 'up' : 'down').'.gif"
									alt="'.$this->l('Up').'" title="'.$this->l('Up').'" /></a>';						}
						else
							echo (int)($tr[$key] + 1);
					}
					elseif (isset($params['image']))
					{
						
						echo '<img src="'._MODULE_DIR_.$params['image'].$tr['image'].'"  height="80" alt="ZadminGallery"/>';
//						// item_id is the product id in a product image context, else it is the image id.
//						$item_id = isset($params['image_id']) ? $tr[$params['image_id']] : $id;
//						// If it's a product image
//						if (isset($tr['id_image']))
//						{
//							$image = new Image((int)$tr['id_image']);
//							$path_to_image = _PS_MODULE_DIR_.'zgallery'.$params['image'].'/'.$image->getExistingImgPath().'.'.$this->imageType;
//						}else
//							$path_to_image = _PS_IMG_DIR_.$params['image'].'/'.$item_id.(isset($tr['id_image']) ? '-'.(int)($tr['id_image']) : '').'.'.$this->imageType;
//						
//						echo cacheImage($path_to_image, $this->table.'_mini_'.$item_id.'.'.$this->imageType, 45, $this->imageType);
					}
					elseif (isset($params['icon']) AND (isset($params['icon'][$tr[$key]]) OR isset($params['icon']['default'])))
						echo '<img src="../img/admin/'.(isset($params['icon'][$tr[$key]]) ? $params['icon'][$tr[$key]] : $params['icon']['default'].'" alt="'.$tr[$key]).'" title="'.$tr[$key].'" />';
					elseif (isset($params['price']))
						echo Tools::displayPrice($tr[$key], (isset($params['currency']) ? Currency::getCurrencyInstance((int)($tr['id_currency'])) : $currency), false);
					elseif (isset($params['float']))
						echo rtrim(rtrim($tr[$key], '0'), '.');
					elseif (isset($params['type']) AND $params['type'] == 'date')
						echo Tools::displayDate($tr[$key], (int)$cookie->id_lang);
					elseif (isset($params['type']) AND $params['type'] == 'datetime')
						echo Tools::displayDate($tr[$key], (int)$cookie->id_lang, true);
					elseif (isset($tr[$key]))
					{
						$echo = ($key == 'price' ? round($tr[$key], 2) : isset($params['maxlength']) ? Tools::substr($tr[$key], 0, $params['maxlength']).'...' : $tr[$key]);
						echo isset($params['callback']) ? call_user_func_array(array($this->className, $params['callback']), array($echo, $tr)) : $echo;
					}
					else
						echo '--';

					echo (isset($params['suffix']) ? $params['suffix'] : '').
					'</td>';
				}

				if ($this->edit OR $this->delete OR ($this->view AND $this->view !== 'noActionColumn'))
				{
					echo '<td class="center" style="white-space: nowrap;">';
					if ($this->view)
						$this->_displayViewLink($token, $id);
					if ($this->edit)
						$this->_displayEditLink($token, $id);
					if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
						$this->_displayDeleteLink($token, $id);
					if ($this->duplicate)
						$this->_displayDuplicate($token, $id);
					echo '</td>';
				}
				echo '</tr>';
			}
		}
	}
	

	/**
	 * Hà hiển thị 
	 * 
	 * @param unknown_type $token
	 */
	public function display($token = NULL)
	{
		global $currentIndex, $cookie;
		
		$this->getList((int)($cookie->id_lang), !$cookie->__get($this->table.'Orderby') ? 'position' : NULL, !$cookie->__get($this->table.'Orderway') ? 'ASC' : NULL);
	//	echo '<h3>'.(!$this->_listTotal ? ($this->l('There are no subcategories')) : ($this->_listTotal.' '.($this->_listTotal > 1 ? $this->l('subcategories') : $this->l('subcategory')))).' '.$this->l('in category').' "'.stripslashes($this->_category->getName()).'"</h3>';
		if ($this->tabAccess['add'] === '1')
			echo '<a href="'.__PS_BASE_URI__.substr($_SERVER['PHP_SELF'], strlen(__PS_BASE_URI__)).'?tab=ZadminGallery&add'.$this->table.'&id_parent='.Tools::getValue('id_zgallery_album').'&token='.($token!=NULL ? $token : $this->token).'"><img src="../img/admin/add.gif" border="0" /> '.$this->l('Add a new SubAlbum').'</a>';
		echo '<div style="margin:10px;">';
		$this->displayList($token);
		echo '</div>';
	}
	/**
	 * Load js và css
	 */
	function loadJS_CSS()
	{
		global $cookie;
		$iso = Language::getIsoById((int)($cookie->id_lang));
		$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
		$ad = dirname($_SERVER["PHP_SELF"]);
		echo '
			<script type="text/javascript">
			var iso = \''.$isoTinyMCE.'\' ;
			var pathCSS = \''._THEME_CSS_DIR_.'\' ;
			var ad = \''.$ad.'\' ;
			</script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>';
		?>
		<script type="text/javascript">
			function copy2friendlyURL()
			{
				$('input#freurl_' + id_language).val(str2url($('input#name_' + id_language).val().replace(/^[0-9]+\./, ''), 'UTF-8'));
			}
		</script>
		<?php
	}
	
	/**
	 * Hiển hị Form 
	 */
	public function displayForm ($isMainTab = true){
		global $currentIndex;	// dia chi index hien tai
		global $cookie;
		parent::displayForm();
		$this->loadJS_CSS();
		if (!($obj = $this->loadObject(true)))
			return;
		$id_zgallery_album=Tools::getValue ('id_zgallery_album');
		$langtags = 'name¤description¤freurl';
		$obj = new  Zalbum ($id_zgallery_album);
		echo '<form action="'.$currentIndex.'&submitAdd'.$this->table.'=1&token='.$this->token.'" method="post" enctype="multipart/form-data">
			'.($obj->id ? '<input type="hidden" name="id_'.$this->table.'" value="'.$obj->id.'" /> ' : '');
		echo '
			<fieldset style="width:900px;">
				<legend>'.$this->l('Album').'</legend>';
				echo $this->addElement('text',array (
										'label' => 'Name',
										'name' => 'name',
										'langtags' => $langtags,
										'width' => 200,
										'note' => '',
										'more' => 'onkeyup="copy2friendlyURL();"'
				),true);
				
				echo '
					<input type="hidden" name="id_parent" value="1">';
		echo $this->addElement('area',array (
									'label' => 'Description',
									'name' => 'description',
									'langtags' => $langtags,
									'width' => 200,
									'note' => '',
									'more' => ''
			),true);
			echo'
				<label>'.$this->l('Image:').' </label>
				<div class="margin-form">';
		echo 		$this->_displayImage($obj->id, _PS_MODULE_DIR_.'zgallery/img/ab/'.Zalbum::getNameImage ($obj->id) ,_MODULE_DIR_.'zgallery/img/ab/'.Zalbum::getNameImage ($obj->id) ,350, NULL, Tools::getAdminToken('ZadminGallery'.(int)(Tab::getIdFromClassName('ZadminGallery')).(int)($cookie->id_lang)), true);
		echo '	<input type="file" name="image" value="'._MODULE_DIR_.'zgallery/img/ab/Album_'.$obj->id.'.jpg"/><sup> *</sup>
					<p>'.$this->l('Upload album logo from your computer').'</p>
					
				</div>
				<div class="clear"></div>';
//		echo $this->addElement('text',array (
//								'label' => 'Friend URL',
//								'name' => 'freurl',
//								'langtags' => $langtags,
//								'width' => 200,
//								'note' => '',
//								'more' => ''
//		),true);
		
		$position = Zalbum::getValueTitle ();
		echo'
				<label>'.$this->l('Menu:').' </label>
				<div class="margin-form">';
					echo '<select style="width: 150px;" name="position">';
					foreach ($position as $value)
						echo '<option '.($value['position']==$obj->position ? 'selected="selected" ' : '').' value="'.$value['position'].'" >'.$value['name'].'</option>';
					echo '</select><p class="clear"></p>';
						
		echo '
			<div class="clear"> </div></div>';
		
		echo $this->addElement('text',array (
								'label' => 'Limit Like',
								'name' => 'limit_like',
								'value' => $obj->limit_like,
								'width' => 50,
								'note' => 'Set 0 if not limited',
								'more' => ''
		));
		
//		echo $this->addElement('text',array (
//								'label' => 'Number view',
//								'name' => 'nb_view',
//								'width' => 50,
//								'value' => $obj->nb_view,
//								'note' => 'Number peoples view album, you can not edit',
//								'more' => 'readonly="readonly"'
//		));
//		
//		echo $this->addElement('text',array (
//								'label' => 'Number Like',
//								'name' => 'nb_like',
//								'width' => 50,
//								'value' => $obj->nb_like,
//								'note' => 'Number peoples like album, you can not edit',
//								'more' => 'readonly="readonly"'
//		));
		echo $this->addElement('text',array (
								'label' => 'Author',
								'name' => 'author',
								'value' => $obj->author,
								'width' => 200,
								'note' => '',
								'more' => ''
		));
		
		echo $this->addElement('text',array (
								'label' => 'Designer',
								'name' => 'designer',
								'value' => $obj->designer,
								'width' => 200,
								'note' => '',
								'more' => ''
		));
		echo $this->addElement('select',array (
								'label' => 'Location',
								'name' => 'location',
								'value' => array (
									'An Giang'
									,'Bà Rịa - Vũng Tàu'
									,'Bạc Liêu'
									,'Bắc Kạn'
									,'Bắc Giang'
									,'Bắc Ninh'
									,'Bến Tre'
									,'Bình Dương'
									,'Bình Định'
									,'Bình Phước'
									,'Bình Thuận'
									,'Cà Mau'
									,'Cao Bằng'
									,'Cần Thơ'
									,'Đà Nẵng'
									,'Đắk Lắk'
									,'Đắk Nông'
									,'Đồng Nai'
									,'Đồng Tháp'
									,'Điện Biên'
									,'Gia Lai'
									,'Hà Giang'
									,'Hà Nam'
									,'Hà Nội'
									,'Hà Tĩnh'
									,'Hải Dương'
									,'Hải Phòng'
									,'Hòa Bình'
									,'Hậu Giang'
									,'Hưng Yên'
									,'TP. Hồ Chí Minh'
									,'Khánh Hòa'
									,'Kiên Giang'
									,'Kon Tum'
									,'Lai Châu'
									,'Lào Cai'
									,'Lạng Sơn'
									,'Lâm Đồng'
									,'Long An'
									,'Nam Định'
									,'Nghệ An'
									,'Ninh Bình'
									,'Ninh Thuận'
									,'Phú Thọ'
									,'Phú Yên'
									,'Quảng Bình'
									,'Quảng Nam'
									,'Quảng Ngãi'
									,'Quảng Ninh'
									,'Quảng Trị'
									,'Sóc Trăng'
									,'Sơn La'
									,'Tây Ninh'
									,'Thái Bình'
									,'Thái Nguyên'
									,'Thanh Hóa'
									,'Thừa Thiên - Huế'
									,'Tiền Giang'
									,'Trà Vinh'
									,'Tuyên Quang'
									,'Vĩnh Long'
									,'Vĩnh Phúc'
									,'Yên Bái'
								),
								'check' => $obj->location,
								'width' => 100,
								'note' => '',
								'more' => ''
		));
		echo $this->addElement('text',array (
								'label' => 'Model',
								'name' => 'model',
								'value' => $obj->model,
								'width' => 200,
								'note' => '',
								'more' => ''
		));
		echo $this->addElement('text',array (
								'label' => 'Style',
								'name' => 'style',
								'value' => $obj->style,
								'width' => 200,
								'note' => '',
								'more' => ''
		));
		echo $this->addElement('text',array (
								'label' => 'Photographer',
								'name' => 'photographer',
								'value' => $obj->photographer,
								'width' => 200,
								'note' => '',
								'more' => ''
		));
		echo $this->addElement('yesno',array (
								'label' => 'Priority view',
								'name' => 'priority_view',
								'width' => 200,
								'value' => $obj->priority_view,
								'note' => '',
								'more' => ''
		),true);
		
		
		
		echo $this->addElement('yesno',array (
								'label' => 'Active',
								'name' => 'active',
								'width' => 200,
								'value' => $obj->active,
								'note' => '',
								'more' => ''
		),true);
		
		echo '
			<div class="margin-form">
					<input type="submit" value="'.$this->l('Save').'" name="submitAdd'.$this->table.'AndBackToParent" class="button" />
				</div>
				<div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
			</fieldset>
		</form>';
	}
}